package com.dcy.modules.system.service;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import com.dcy.common.constant.Constant;
import com.dcy.common.constant.RedisConstant;
import com.dcy.modules.system.dto.output.LoginOutputDTO;
import com.dcy.system.mapper.ResourceMapper;
import com.dcy.system.mapper.RoleMapper;
import com.dcy.system.model.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author：dcy
 * @Description:
 * @Date: 2021/4/2 15:14
 */
@Service
public class AuthService {

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private ResourceMapper resourceMapper;


    /**
     * 设置权限
     *
     * @param userId
     * @return
     */
    public Set<String> getAuthRoleAndResourceByUserId(String userId) {
        // 查询权限
        List<String> resourcesCodeList = getPermissionListByUserId(userId);
        List<String> roleKeyList = getAuthRoleListByUserId(userId).stream().map(Role::getRoleKey).collect(Collectors.toList());
        Set<String> roleSet = CollUtil.newHashSet(resourcesCodeList);
        CollUtil.addAll(roleSet, roleKeyList);
        return roleSet;
    }

    /**
     * 根据用户id 刷新session里面的用户信息，只能修改登录人
     *
     * @param userId
     */
    public void refreshUserInfoByUserId(String userId) {
        Optional.ofNullable(StpUtil.getSessionByLoginId(userId, false)).ifPresent(session -> {
            List<String> authRoleAndResourceByUserId = getPermissionListByUserId(userId);
            LoginOutputDTO loginOutputDTO = session.getModel(Constant.SESSION_USER_KEY, LoginOutputDTO.class);
            loginOutputDTO.setResources(CollUtil.newHashSet(authRoleAndResourceByUserId));
            session.set(Constant.SESSION_USER_KEY, loginOutputDTO);
        });
    }

    /**
     * 根据用户id查询权限集合
     *
     * @param userId
     * @return
     */
    @Cacheable(value = RedisConstant.REDIS_USER_RESOURCE, key = "#userId")
    public List<String> getPermissionListByUserId(String userId) {
        List<String> resourcesCodeList = new ArrayList<>();
        final List<Role> roles = getAuthRoleListByUserId(userId);
        for (Role role : roles) {
            final List<String> permissionList = resourceMapper.selectPermissionListByRoleId(role.getId());
            resourcesCodeList.addAll(permissionList);
        }
        return resourcesCodeList.stream().distinct().collect(Collectors.toList());
    }

    /**
     * 根据用户id查询角色集合
     *
     * @param userId
     * @return
     */
    @Cacheable(value = RedisConstant.REDIS_USER_ROLE, key = "#userId")
    public List<Role> getAuthRoleListByUserId(String userId) {
        return roleMapper.selectRoleListByUserId(userId);
    }
}
